﻿@using TamoCRM.Core
@using TamoCRM.Core.Commons.Utilities
@model TamoCRM.Web.Mvc.Areas.Admin.Models.Contacts.ContactCreateModel

@{
    ViewBag.Title = "Trộn Contact & Đưa TVTS";
    Layout = "~/Areas/Admin/Views/Shared/_Layout.cshtml";

    var lstLevels = ViewBag.Levels;
    var lstMajors = ViewBag.Majors;
    var lstSchools = ViewBag.Schools;
}

<div class="breadcrumbs" id="breadcrumbs">
    <script type="text/javascript">
        try {
            ace.settings.check('breadcrumbs', 'fixed');
        }
        catch (e) {

        }
    </script>

    <ul class="breadcrumb">
        <li>
            <i class="icon-home home-icon"></i>
            <a href="/Home">Trang chủ</a>
        </li>

        <li>
            <a href="javascript:void(0);">Danh mục</a>
        </li>
        <li class="active">Contact</li>
    </ul>
</div>

<div class="page-content">
    <div class="page-header">
        <h1>Trộn Contact & Đưa TVTS</h1>
    </div>
    <!-- /.page-header -->

    <div class="row">
        <div class="col-xs-12">
            <!-- PAGE CONTENT BEGINS -->
            @using (Ajax.BeginForm("FilterContactHandover", "Contact", new AjaxOptions { HttpMethod = "POST" }, new { enctype = "multipart/form-data", @class = "form-horizontal", role = "form", id = "filter_contact_handover_form" }))
            {
                @Html.AntiForgeryToken()
                <div class="form-group">
                    <div class="col-sm-12" id="alert">
                    </div>
                </div>
                <div class="form-group" style="margin-bottom: 5px;">
                    <div class="col-sm-2 bolder">
                        Kho Contact
                    </div>
                    <div id="lblMo" class="col-sm-5 bolder">
                        Lọc cho MO
                    </div>
                     <div id="lblCc" class="col-sm-5 bolder">
                        Lọc cho CC (L2+)
                    </div>
                    <div class="col-sm-5">
                        <button id="btnGoFilter" class="btn-primary">Lọc Contact</button>
                        <label>Số contact lọc trong kho: </label>
                        <input type="text" readonly="readonly" id="lblAmountFilter" style="width: 60px; font-weight: bold;" />
                    </div>
                </div>
                <div class="form-group" style="height: 150px;">
                    <div class="col-sm-2">
                        <div style="border: 1px solid #c5d0dc; padding: 15px; height: 150px;">
                            <input type="radio" name='SourceType' id='rdbHot' checked value="@ConvertHelper.ToInt32((int)SourceType.HOT)" />
                            <label>Hot</label>
                            <br />
                            <input type="radio" name='SourceType' id='rdbMo' value="@ConvertHelper.ToInt32((int)SourceType.MO)" />
                            <label>MO</label>
                            <br />
                            <input type="radio" name='SourceType' id='rdbCc' value="@ConvertHelper.ToInt32((int)SourceType.CC)" />
                            <label>CC (L2+)</label>
                            <br />
                            <input type="radio" name='SourceType' id='rdbReuse' value="@ConvertHelper.ToInt32((int)StatusType.ContactReuse)" />
                            <label>Tái sử dụng</label>
                        </div>
                    </div>
                    <div id="divMo" class="col-sm-5" style="border: 1px solid #c5d0dc; padding: 15px 10px 10px 10px;">
                        <div class="col-sm-6" style="height: 123px; overflow-y: auto;">
                            <label class="bolder">Trường</label><br />
                            @foreach (var item in lstSchools)
                            {
                                <input type="checkbox" name='@(item.SchoolId)_chkSchool' id='@(item.SchoolId)_chkSchool' />
                                <label for="@(item.SchoolId)_chkSchool">@item.Name</label>
                                <br />
                            }
                        </div>
                        <div class="col-sm-1">&nbsp;</div>
                        <div class="col-sm-5" style="height: 113px; overflow-y: auto;">
                            <label class="bolder">Ngành</label><br />
                            @foreach (var item in lstMajors)
                            {
                                <input type="checkbox" name='@(item.MajorId)_chkMajor' id='@(item.MajorId)_chkMajor' />
                                <label for="@(item.MajorId)_chkMajor">@item.Name</label>
                                <br />
                            }
                        </div>
                    </div>
                    <div id="divCC" class="col-sm-5" style="border: 1px solid #c5d0dc; padding: 15px 10px 10px 10px;">
                        <div class="col-sm-12" style="height: 123px; overflow-y: auto;">
                            <label class="bolder">Level</label><br />
                            @foreach (var item in lstLevels)
                            {
                                if (item.LevelId >= 2)
                                {
                                <div class="col-sm-2">
                                    <input type="checkbox" name='chkLevels' id='@(item.LevelId)_chkLevel' />
                                    <label for="@(item.LevelId)_chkLevel">@item.Name</label>
                                </div>
                                }
                            }
                        </div>
                    </div>
                    <div class="col-sm-5">
                        <div style="border: 1px solid #c5d0dc; padding: 15px 15px 10px 15px; height: 150px;">
                            <div class="form-group">
                                <div class="col-sm-3">
                                    <label>Số lượng </label>
                                </div>
                                <div class="col-sm-9">
                                    @Html.TextBox("txtAmount", "0", "number", new { type = "number", min = "0", max = "10000" })
                                </div>
                            </div>
                            <div class="form-group" style="margin-bottom: 0px;">
                                <div class="col-sm-3">
                                    <label>Cách chia</label>
                                </div>
                                <div class="col-sm-9">
                                    <input type="radio" name='divide' id='rdbSame' checked />
                                    <label>Phân đều, lần lượt</label>
                                    <br />
                                    <input type="radio" name='divide' id='rdbRatio' />
                                    <label>Phân theo tỷ lệ</label>
                                    <br />
                                    <input type="radio" name='divide' id='rdbEnough' />
                                    <label>Phân cho đủ chỉ tiêu</label>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            }

            <div class="space-6"></div>
            <button id="btnClearDraft" class="btn-primary" style="float: left; margin-right: 10px;">Xóa toàn bộ</button>
            <button id="btnSaveDraft" class="btn-primary" style="float: left; margin-right: 10px;">Lưu nháp</button>
            <button id="btnDivide" class="btn-primary" style="float: left; margin-right: 10px;">Chia nháp tự động</button>
            <button id="btnSubmit" class="btn-primary" style="float: right;">Trộn & Đưa TVTS</button>
            @Html.TextBox("HandoverDate", DateTime.Now.ToString("dd/MM/yyyy"), new { @style = "float: right; height: 25px; margin-right: 10px; width: 100px; " })
            <label style="float: right; margin-right: 10px; margin-top: 2px;">Bàn giao cho ngày</label>
            <div class="clearfix"></div>

            <div class="space-6"></div>
            <table id="grid-table"></table>
            <!-- PAGE CONTENT ENDS -->
        </div>
        <!-- /.col -->
    </div>
    <!-- /.row -->
</div>

<script type="text/javascript">
    var url = 'admin/api/user/getdraft?branchId={0}';
    var grid_selector = "#grid-table";
    var heades = ['Id', 'Nhóm', 'Họ và tên', 'Nháp trước đó', 'Nháp hiện tại', 'Tổng số', 'Chỉ tiêu TVTS'];
    var model = [
        { name: 'Id', index: 'Id', editable: false, sorttype: 'string', editoptions: { disabled: true }, width: '0px' },
        { name: 'GroupName', index: 'GroupName', editable: false, sorttype: 'string' },
        { name: 'FullName', index: 'FullName', editable: false, sorttype: 'string' },
        { name: 'Draft', index: 'Draft', editable: false, sorttype: 'int' },
        { name: 'DraftNew', index: 'DraftNew', editable: true, sorttype: 'int', formatter: inputNumberFomatter },
        { name: 'Amount', index: 'Amount', editable: false, sorttype: 'int' },
        { name: 'Norms', index: 'Norms', editable: false, sorttype: 'int' }
    ];
    $(document).ready(function () {
        $('#HandoverDate').datepicker({ format: 'dd/mm/yyyy', autoclose: true, dateonly: true, startDate: "+0d" });

        hideMo();
        hideCC();
        var branchId = '@ViewBag.BranchId';
        setupGridTable("#grid-table", "", url.format(branchId), "admin/api/user/edit", "Id", "Danh sách trộn contact", heades, model, "", 1000, '350px');

        $("#btnGoFilter").click(function (e) {
            e.preventDefault();

            var majors = $('#rdbMo').is(':checked') ? buildParamMajors() : '';
            var schools = $('#rdbMo').is(':checked') ? buildParamSchools() : '';
            var levels = $('#rdbCc').is(':checked') ? '@ConvertHelper.ToString((int)LevelType.L2)' : '';
            var typeId = $('#rdbHot').is(':checked') ? $('#rdbHot').val() : $('#rdbMo').is(':checked') ? $('#rdbMo').val() : $('#rdbCc').is(':checked') ? $('#rdbCc').val() : 0;
            var statusIds = $('#rdbHot').is(':checked')
                ? '@((int)StatusType.HandoverToDistributor)'
                : $('#rdbMo').is(':checked')
                    ? '@((int)StatusType.HandoverToDistributor)'
                    : $('#rdbCc').is(':checked')
                        ? '@((int)StatusType.HandoverToDistributor)' + ',' + '@((int)StatusType.AcceptedL2FromCollaborator)'
                        : '@((int)StatusType.ContactReuse)';

            var newUrl = "/admin/api/contact/filtercounthandover?typeid={0}&statusIds={1}&levels={2}&schools={3}&majors={4}&branchId={5}".format(typeId, statusIds, levels, schools, majors, branchId);

            $.ajax({
                type: 'GET',
                url: newUrl,
                success: function (data) {
                    $('#lblAmountFilter').val(data);
                },
                error: function (request, status, ex) {
                    $("#alert").addClass("alert alert-block alert-error");
                    $("#alert").html("Lọc contact không thành công.");
                }
            });
        });
        $("#btnDivide").click(function (e) {
            e.preventDefault();
            var total = parseInt($('#lblAmountFilter').val());
            if (total <= 0) {
                alert('Số lượng lọc trong kho không có, thử lại sau!');
                return;
            }
            var amount = parseInt($('#txtAmount').val());
            if (amount <= 0) {
                alert('Số lượng cần chia bằng 0, thử lại sau!');
                return;
            }
            if (amount > total) {
                alert('Số lượng cần chia lớn hơn số lượng lọc trong kho, thử lại sau!');
                return;
            }

            var majors = buildParamMajors();
            var schools = buildParamSchools();
            var levels = $('#rdbCc').is(':checked') ? '@ConvertHelper.ToString((int)LevelType.L2)' : '';
            var typeId = $('#rdbHot').is(':checked') ? $('#rdbHot').val() : $('#rdbMo').is(':checked') ? $('#rdbMo').val() : $('#rdbCc').is(':checked') ? $('#rdbCc').val() : 0;
            var statusIds = $('#rdbHot').is(':checked')
                ? '@((int)StatusType.HandoverToDistributor)'
                : $('#rdbMo').is(':checked')
                    ? '@((int)StatusType.HandoverToDistributor)'
                    : $('#rdbCc').is(':checked')
                        ? '@((int)StatusType.HandoverToDistributor)' + ',' + '@((int)StatusType.AcceptedL2FromCollaborator)'
                        : '@((int)StatusType.ContactReuse)';

            var diviceType = $('#rdbSame').is(':checked')
                ? '@ConvertHelper.ToString((int)DiviceType.Same)'
                : $('#rdbRatio').is(':checked')
                    ? '@ConvertHelper.ToString((int)DiviceType.Ratio)'
                    : '@ConvertHelper.ToString((int)DiviceType.Enough)';

            // Format Url
            var newUrl = "/admin/api/user/divicedraft?typeid={0}&statusIds={1}&levels={2}&schools={3}&majors={4}&amount={5}&branchId={6}&diviceType={7}".format(typeId, statusIds, levels, schools, majors, amount, branchId, diviceType);
            jQuery(grid_selector).jqGrid().setGridParam({ url: newUrl }).trigger("reloadGrid");
        });
        $("#btnSaveDraft").click(function (e) {
            e.preventDefault();
            var total = parseInt($('#txtAmount').val());
            var amount = 0;
            var rows = $('input[name="cellAmount"]');
            for (var i = 0; i < rows.length; i++) {
                var value = parseInt(rows[i].value);
                amount += value;
            }
            if (amount > total) {
                alert('Số lượng chia hiện tại lớn hơn số lượng cần chia, thử lại sau!');
                return;
            }

            var majors = buildParamMajors();
            var schools = buildParamSchools();
            var total = $('#txtAmount').val();
            var levels = $('#rdbCc').is(':checked') ? '@ConvertHelper.ToString((int)LevelType.L2)' : '';
            var typeId = $('#rdbHot').is(':checked') ? $('#rdbHot').val() : $('#rdbMo').is(':checked') ? $('#rdbMo').val() : $('#rdbCc').is(':checked') ? $('#rdbCc').val() : 0;
            var statusIds = $('#rdbHot').is(':checked')
               ? '@((int)StatusType.HandoverToDistributor)'
                : $('#rdbMo').is(':checked')
                    ? '@((int)StatusType.HandoverToDistributor)'
                    : $('#rdbCc').is(':checked')
                        ? '@((int)StatusType.HandoverToDistributor)' + ',' + '@((int)StatusType.AcceptedL2FromCollaborator)'
                        : '@((int)StatusType.ContactReuse)';

            var users = '';
            var amounts = '';
            var rows = $("#grid-table").getDataIDs();
            for (i = 1; i < rows.length + 1; i++) {
                users += i == 1 ? $('#grid-table').jqGrid('getCell', i, 'Id') : ',' + $('#grid-table').jqGrid('getCell', i, 'Id');
                var numId = $($('#grid-table').jqGrid('getCell', i, 'DraftNew')).attr('id');
                amounts += i == 1
                    ? $('#' + numId).val()
                    : ',' + $('#' + numId).val();
            }

            var newUrl = '/admin/api/contact/savedraft';
            $.post("/admin/api/contact/savedraft", {
                typeId: typeId,
                statusIds: statusIds,
                levels: levels,
                schools: schools,
                majors: majors,
                total: total,
                branchId: branchId,
                users: users,
                amounts: amounts
            }).done(function (data) {
                $("#alert").addClass("alert alert-block alert-success");
                $("#alert").html(data);

                // Format Url
                $("#btnGoFilter").click();
                newUrl = "/admin/api/user/getdraft?branchId={0}".format(branchId);
                jQuery(grid_selector).jqGrid().setGridParam({ url: newUrl }).trigger("reloadGrid");
            });
        });
        $("#btnSubmit").click(function (e) {
            e.preventDefault();

            $.ajax({
                type: 'POST',
                url: '/admin/api/contact/handover',
                data: {
                    branchId: branchId,
                    datetime: $('#HandoverDate').val(),
                },
                beforeSend: function () {
                    alertProcess();
                },
                success: function (response) {
                    alertSuccess("Trộn & đưa TVTS thành công " + response + " contacts");
                    $("#btnGoFilter").click();

                    // Format Url
                    var newUrl = '/admin/api/user/getdraft?branchId={0}'.format(branchId);
                    jQuery(grid_selector).jqGrid().setGridParam({ url: newUrl }).trigger("reloadGrid");
                },
                error: function (request, status, ex) {
                    alertError("Hệ thống bị lỗi, Trộn & đưa TVTS không thành công.");
                }
            });
        });
        $("#btnClearDraft").click(function (e) {
            e.preventDefault();

            $.ajax({
                type: 'GET',
                url: '/admin/api/contact/cleardraft',
                success: function (data) {
                    $("#alert").addClass("alert alert-block alert-success");
                    $("#alert").html(data);

                    // Format Url
                    $("#btnGoFilter").click();
                    newUrl = "/admin/api/user/getdraft?branchId={0}".format(branchId);
                    jQuery(grid_selector).jqGrid().setGridParam({ url: newUrl }).trigger("reloadGrid");
                },
                error: function (request, status, ex) {
                    $("#alert").addClass("alert alert-block alert-error");
                    $("#alert").html("Lọc contact không thành công.");
                }
            });
        });
        $('input[name="SourceType"]').click(function (e) {
            if ($("#rdbMo").is(':checked')) showMo();
            else hideMo();
            
            if ($("#rdbCc").is(':checked')) showCC();
            else hideCC();
        });
    });

    function hideMo() {
        $('#divMo').css('display', 'none');
        $('#lblMo').css('display', 'none');
        $('#divMo input[type=checkbox]').each(function () {
            $(this).prop('checked', false);
        });
    }

    function showMo() {
        $('#divMo').css('display', '');
        $('#lblMo').css('display', '');
    }

    function hideCC() {
        $('#divCC').css('display', 'none');
        $('#lblCc').css('display', 'none');
        $('#divCC input[type=checkbox]').each(function () {
            $(this).prop('checked', false);
        });
    }
    
    function showCC() {
        $('#divCC').css('display', '');
        $('#lblCc').css('display', '');
    }

    function checkDraftNew(elm, rowId) {
        var name = $('#grid-table').jqGrid('getCell', rowId, 'FullName');
        var draft = parseInt($('#grid-table').jqGrid('getCell', rowId, 'Draft'));
        var norms = parseInt($('#grid-table').jqGrid('getCell', rowId, 'Norms'));
        var total = parseInt(elm.value) + draft;
        if (total > norms) {
            alert('Số lượng được giao cho ' + name + ' lớn hơn chỉ tiêu, thử lại sau!');
            elm.value = norms - draft;
            return;
        }
        $('#grid-table').jqGrid("setCell", rowId, 'Amount', total);
    }

    function inputNumberFomatter(cellvalue, options, rowObject) {
        var rowId = options.rowId;
        return '<input id="' + rowObject.Id + '_Amount" max="10000" min="0" name="cellAmount" type="number" value="' + cellvalue + '" onchange="checkDraftNew(this, ' + rowId + ')">';
    }
</script>
